<?php

namespace Admin\Controller;
use Admin\Logic\GoodsLogic;
use Think\AjaxPage;
use Admin\Model\GoodsModel ; 
use Think\Upload ; 

/**
 * 商品控制器类
 * @author vardump@foxmail.com
 */
class ShopController extends AdminController {
	public function index(){
		$this->display();
	}
    //统计
    function statistics(){
        $this->display('index');
    }

    //订单 
    function orders(){
        $this->display('index');
    }

    //发货单 
    function send(){
    }
    //优惠券 
    function coupon(){        
        $this->display('index');

    }
    function credits(){
        $this->display('index');
    }
    function payments(){
        $this->display('index');
    }
    function aftersale(){
        $this->display('index');
    }

	public function category(){           
	        $GoodsLogic = new GoodsLogic();               
	        $cat_list = $GoodsLogic->goods_cat_list();
	        $this->assign('cat_list',$cat_list);        
	        $this->display(); 
	}

	function addEditCategory(){
			 $GoodsLogic = new GoodsLogic();        
            if(IS_GET)
            {
                $goods_category_info = D('GoodsCategory')->where('id='.I('GET.id',0))->find();                                                            
                $level_cat = $GoodsLogic->find_parent_cat($goods_category_info['id']); // 获取分类默认选中的下拉框
                
                $cat_list = M('goods_category')->where("parent_id = 0")->select(); // 已经改成联动菜单                
                $this->assign('level_cat',$level_cat);                
                $this->assign('cat_list',$cat_list);                 
                $this->assign('goods_category_info',$goods_category_info);   
                $this->display();     
                exit;
            }

            $GoodsCategory = D('GoodsCategory'); //

            $type = $_POST['type'] > 0 ? 2 : 1; // 标识自动验证时的 场景 1 表示插入 2 表示更新                        
            //ajax提交验证
            if($_GET['is_ajax'] == 1)
            {
                C('TOKEN_ON',false);
                $_POST['parent_id'] = ($_POST['parent_id_2'] == 0) ? intval($_POST['parent_id_1']) : intval($_POST['parent_id_2']) ; 
                $_POST['image'] = NULL ; 
                $_POST['cat_group'] = 0 ; 
                $_POST['commission_rate'] = 0 ; 
                $_POST['mobile_name'] = htmlspecialchars($_POST['name']) ; 
                //分类只能有两级 . 顶级分类不能为是否机考 .
                if($_POST['parent_id'] == 0 ){
                    $_POST['is_test'] = 0 ;
                    $_POST['level'] = 1 ;
                }else{
                    $_POST ['level'] = 2; 
                }
                if(isset($_POST['id'])){
                    //更新  .
                    if($_POST['id'] == $_POST['parent_id']) {
                        $this->error('上级分类不能为自己');
                    }
                    if($_POST['parent_id'] == 0 ){
                        $_POST['parent_id_path'] = '0_' . $_POST['id'] ;
                    }else{
                        $_POST['parent_id'] = find_post_parent_id($_POST['parent_id']);
                        $_POST['parent_id_path'] = '0_' . $_POST['parent_id'] . '_' . $_POST['id'] ; 
                    }
                    if(M('GoodsCategory')->where(array('id' => $_POST['id']))->save($_POST)){
                        $this->success('更新成功');
                    }else{
                        $this->error('更新失败');
                    }
                    exit;
                }else{
                    //插入  .
                    $id = M('GoodsCategory')->add($_POST);

                    if($_POST['parent_id'] == 0 ){
                        $path = '0_' . $id ; 
                    }else{
                        //查找上级分类属于哪个 。
                        $_POST['parent_id'] = find_post_parent_id($_POST['parent_id']);

                        $path = '0_' . $_POST['parent_id'] . '_' . $id ; 
                    }

                    M('GoodsCategory')->where(array('id' => $id))->save(array('parent_id_path'=>$path,'parent_id'=>$_POST['parent_id']));
                    $this->success('增加成功');
                    exit;
                }
            }
 
		$this->display();  

	}

     /**
     * 删除分类
     */
    public function delGoodsCategory(){
        // 判断子分类
        $GoodsCategory = M("GoodsCategory");                
        $count = $GoodsCategory->where("parent_id = {$_GET['id']}")->count("id");   
        $count > 0 && $this->error('该分类下还有分类不得删除!',U('Admin/Shop/category'));
        // 判断是否存在商品
        $goods_count = M('Goods')->where("cat_id = {$_GET['id']}")->count('1');
        $goods_count > 0 && $this->error('该分类下有商品不得删除!',U('Admin/Shop/category'));
        // 删除分类
        $GoodsCategory->where("id = {$_GET['id']}")->delete();   
        $this->success("操作成功!!!",U('Admin/Shop/category'));
    }

    /**
     * 商品列表
     */
    function goodslist(){
        $GoodsLogic = new GoodsLogic();        
        $brandList = $GoodsLogic->getSortBrands();
        $categoryList = $GoodsLogic->getSortCategory();
        $this->assign('categoryList',$categoryList);
        $this->assign('brandList',$brandList);
        $this->display();   
    }

    /**
     * ajax加载商品
     */
    function ajaxGoodsList(){
         $where = ' 1 = 1 '; // 搜索条件                
        I('intro')    && $where = "$where and ".I('intro')." = 1" ;        
        I('brand_id') && $where = "$where and brand_id = ".I('brand_id') ;
        (I('is_on_sale') !== '') && $where = "$where and is_on_sale = ".I('is_on_sale') ;                
        $cat_id = I('cat_id');
        // 关键词搜索               
        $key_word = I('key_word') ? trim(I('key_word')) : '';
        if($key_word)
        {
            $where = "$where and (goods_name like '%$key_word%' or goods_sn like '%$key_word%')" ;
        }
        
        if($cat_id > 0)
        {
            $grandson_ids = getCatGrandson($cat_id); 
            $where .= " and cat_id in(".  implode(',', $grandson_ids).") "; // 初始化搜索条件
        }
        
        
        $model = M('Goods');
        $count = $model->where($where)->count();
        $Page  = new AjaxPage($count,10);
        /**  搜索条件下 分页赋值
        foreach($condition as $key=>$val) {
            $Page->parameter[$key]   =   urlencode($val);
        }
        */
        $show = $Page->show();
        $order_str = "`{$_POST['orderby1']}` {$_POST['orderby2']}";
        $goodsList = $model->where($where)->order($order_str)->limit($Page->firstRow.','.$Page->listRows)->select();

        $catList = D('goods_category')->select();
        $catList = convert_arr_key($catList, 'id');
        $this->assign('catList',$catList);
        $this->assign('goodsList',$goodsList);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();         
    }

    /**
     * 增加新商品
     */
    function addEditGoods(){


        $goods = D('Goods');
        if( IS_POST){
                $original_img = '';
                $count = count($_FILES['original_img']['name']) ; 
                if($count >= 1 && !empty($_FILES['original_img']['name'][0])){
                      $upload = new Upload();
                      $info = $upload->upload();
                      if(!$info){
                        $this->error($upload->getError());
                      }else{
                        foreach($info as $key => $val){
                           $original_img .= $upload->rootPath . $val['savepath'] . $val['savename'] . ',' ;  
                        }
                        $original_img = substr($original_img , 0 , strlen($original_img) -1 );
                      }
                }
            if(isset($_POST['goods_id'])){
                if($res = $goods->create()){
                    if($original_img != ''){
                        $res ['original_img'] = $original_img ; 
                    }
                    if($goods->save()){
                        $this->success('更新成功');
                    }
                }else{
                    $this->error($goods->getError());
                }
                exit;
            }else{
                //插入操作 
                if(isset($_FILES['original_img'])){
                    if($res = $goods->create()){
                        $res ['original_img'] =  $original_img;
                        $goods->add($res);
                        $this->success('新增成功');
                    }else{
                        $this->error($goods->getError());
                    }
                    exit;
                }
            }
        }
        if(isset($_GET['id'])){
            $info = $goods->find(intval($_GET['id']));
            //获取上级分类
            $parent = M('goods_category')->find($info['cat_id']);
            $info ['parent_id'] =  M('goods_category')->find($parent['parent_id'])['id'];
            $this->assign('info',$info);
        }
        $this->assign('current' , 1);
        $this->assign('panel' ,$panel);
        $this->display();
    }

    /**
     * 动态获取商品属性输入框 根据不同的数据返回不同的输入框类型
     */
    public function ajaxGetAttrInput(){
        $GoodsLogic = new GoodsLogic();
        $str = $GoodsLogic->getAttrInput($_REQUEST['goods_id'],$_REQUEST['type_id']);
        exit($str);
    }

     /**
     * 动态获取商品规格选择框 根据不同的数据返回不同的选择框
     */
    public function ajaxGetSpecSelect(){
        $goods_id = $_GET['goods_id'] ? $_GET['goods_id'] : 0;        
        $GoodsLogic = new GoodsLogic();
        //$_GET['spec_type'] =  13;
        $specList = D('Spec')->where("type_id = ".$_GET['spec_type'])->order('`order` desc')->select();
        foreach($specList as $k => $v)        
            $specList[$k]['spec_item'] = D('SpecItem')->where("spec_id = ".$v['id'])->getField('id,item'); // 获取规格项                
        
        $items_id = M('SpecGoodsPrice')->where('goods_id = '.$goods_id)->getField("GROUP_CONCAT(`key` SEPARATOR '_') AS items_id");
        $items_ids = explode('_', $items_id);       
        
        // 获取商品规格图片                
        if($goods_id)
        {
           $specImageList = M('SpecImage')->where("goods_id = $goods_id")->getField('spec_image_id,src');                 
        }        
        $this->assign('specImageList',$specImageList);
        
        $this->assign('items_ids',$items_ids);
        $this->assign('specList',$specList);
        $this->display('ajax_spec_select');        
    } 


     /**
     * 动态获取商品规格输入框 根据不同的数据返回不同的输入框
     */    
    public function ajaxGetSpecInput(){     
         $GoodsLogic = new GoodsLogic();
         $goods_id = $_REQUEST['goods_id'] ? $_REQUEST['goods_id'] : 0;
         $str = $GoodsLogic->getSpecInput($goods_id ,$_POST['spec_arr']);
         exit($str);   
    }


        /**
     * 删除商品
     */
    public function delGoods()
    {
        $goods_id = $_GET['id'];
        $error = '';
        
        // 判断此商品是否有订单
      //  $c1 = M('OrderGoods')->where("goods_id = $goods_id")->count('1');
      //  $c1 && $error .= '此商品有订单,不得删除! <br/>';
        
        
         // 商品团购
     //   $c1 = M('group_buy')->where("goods_id = $goods_id")->count('1');
    //    $c1 && $error .= '此商品有团购,不得删除! <br/>';   
        
         // 商品退货记录
   //     $c1 = M('return_goods')->where("goods_id = $goods_id")->count('1');
   //     $c1 && $error .= '此商品有退货记录,不得删除! <br/>';
        
        if($error)
        {
            $return_arr = array('status' => -1,'msg' =>$error,'data'  =>'',);   //$return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);        
            $this->ajaxReturn(json_encode($return_arr));            
        }
        
        // 删除此商品      

        M("Goods")->where('goods_id ='.$goods_id)->delete();  //商品表
        M("cart")->where('goods_id ='.$goods_id)->delete();  // 购物车
        M("comment")->where('goods_id ='.$goods_id)->delete();  //商品评论
        M("goods_consult")->where('goods_id ='.$goods_id)->delete();  //商品咨询
        M("goods_images")->where('goods_id ='.$goods_id)->delete();  //商品相册
        M("spec_goods_price")->where('goods_id ='.$goods_id)->delete();  //商品规格
        M("spec_image")->where('goods_id ='.$goods_id)->delete();  //商品规格图片
        M("goods_collect")->where('goods_id ='.$goods_id)->delete();  //商品收藏          
                     
        $return_arr = array('status' => 1,'msg' => '操作成功','data'  =>'',);   //$return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);        
        $this->ajaxReturn(json_encode($return_arr));
    }

    //物流设置 
    function wuliu(){
        if(IS_POST){
            $type = I('post.type') ; 
            if('change' == $type){
                $map = array(
                    'shipping_id' => I('post.id'),
                  ) ;
                $data = array('enabled' => I('post.status')) ; 
                M('Shipping')->where($map)->save($data);
                $this->success('成功');
            }

        }
        if(isset($_GET['type'])){
            $this->display('wuliu_type');
        }else{
            $list = $this->lists('Shipping'); 
            $this->assign('_list' , $list);
            $this->display();
        }
    }

    //物流编辑 
    function edit(){
        if(IS_POST){
            $id = I('post.shipping_id');
            if(!$id){
                M('Shipping')->add(I('post.'));
            }else{
                M('Shipping')->where(array('shipping_id'=>$id))->save(I('post.'));
            }
            $this->success('成功');
        }
        if(isset($_GET['id'])){

            $this->assign('id' , $_GET['id']);
            $this->assign('info' , M('Shipping')->where('shipping_id=' . $_GET['id'])->find());
        }
       
        $this->display();
    }

    //配置列表
    function config($code = ''){
        if(!$code){
            $this->error('错误');
        }

        $_list = $this->lists('ShippingArea' , array('shipping_code' => $code));
        // $arr = array();
        // foreach($_list as $k => $v){
        //     $arr []  = unserialize($v['config']);
        // }
        // dump($arr);
        $this->assign('_list' , $_list);
        $this->display();
    }

    //增加物流配置 
    function add_shipping_config($id = NULL ){
        if(IS_POST){
            $post = I('post.');
            $data ['config'] = serialize(array(
                'first_weight' => $post['first_weight'] , 
                'second_weight' => $post ['second_weight'] , 
                'ids' => $post['ids'] ,
                'money' => floatval($post['money']) , 
                'add_money' => floatval($post['money']) , 
            ));
            $data ['shipping_area_name'] = $post ['shipping_area_name']  ; 
            $data ['shipping_area_code'] = $post ['shipping_area_code']  ; 
            $id = I('post.id');
            if($id){
                M('ShippingArea')->where('shipping_area_id=' . $id)->save($data);
            }else{
                M('ShippingArea')->add($data);
            }
            $this->success('成功');
        }

        if($id){
            $data = M('ShippingArea')->where('shipping_area_id=' . $id)->find();
            if($data){
                $data ['config'] = unserialize($data['config']);
            }
            $this->assign('config' , $data);
        }

        /***  缓存 **/
        $region = S('region_level_1') ;
        if(!$region){
            $region = M('Region')->where('parent_id=0')->select();
            $region = S('region_level_1' , $region , 24 * 3600 ) ;
        }
        $this->assign('region' , $region);
        $this->display();
    }

}
